// 导入类型、模块
import type { RouteLocationNormalized, NavigationGuardNext } from 'vue-router'

import { useTabsStore } from '@/stores/tabs'

import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useLoading } from '@/hooks/useLoading'

const { show, hide } = useLoading()

// 刷新网页就会执行
let isRefresh = true

// 导航守卫（网页刷新&路由变化都执行）
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
	NProgress.start()
	next()

	if (isRefresh) {
		show()
		isRefresh = false // 切记除非网页刷新否则一直是false不再执行

		// 刷新网页保留当前Tabs
		if (!['/', '/analysis'].includes(to.path)) {
			const tabsStore = useTabsStore()
			const { handleTabsAdd } = tabsStore
			handleTabsAdd({
				// 触发当前路由点击
				path: to.path,
				label: to.meta.title as string
			})
		}
	}
})

router.afterEach(() => {
	if (!isRefresh) hide()
	NProgress.done()
})
